<?php

class Database {		
	private $host = "localhost";
	private $dbase="ans";
	private $user = "root";
	private $password = "";
	public $table_name='';
	public static $connection = null;
	
	function __construct() {
		if( self::$connection == null ) {
			$this->connection=mysql_connect($this->host,$this->user,$this->password) or die ("Cannot connect: 100");		
			mysql_select_db($this->dbase) or die ("Cannot select db: 101 ");
		}
	}	
	
	public function last_insert_id(){
		return mysql_result(mysql_query("SELECT last_insert_id()"),0);
	}
	
	public function insert($arr){
		
		foreach($arr as $key => $value){
			$ins_fields[]=mysql_real_escape_string($key);
			$ins_values[]="'".mysql_real_escape_string($value)."'";
		}
		$fields=implode(",",$ins_fields);
		$values=implode(",",$ins_values);
		
		mysql_query("INSERT INTO $this->table_name ( $fields ) VALUES ( $values )") or die ("Cannot execute: 102");
		
		if(mysql_affected_rows()==1)
			return $this->last_insert_id();
	
		return 0;	
	}
	
	public function update($arr,$id){		
		$id=mysql_real_escape_string($id);
		
		foreach($arr as $key => $value)
			$ins_fields[]=mysql_real_escape_string($key)."='".mysql_real_escape_string($value)."'";			
		
		$fields=implode(",",$ins_fields);		
		
		mysql_query("UPDATE $this->table_name SET $fields WHERE id='$id' ") or die ("Cannot execute: 103");
		
		if(mysql_affected_rows()==1)
			return $id;
	
		return 0;	
	}
	
	public function delete($id){
		$id=mysql_real_escape_string($id);
		
        //echo "DELETE FROM $this->table_name WHERE id='$id' ";
		mysql_query("DELETE FROM $this->table_name WHERE id='$id' ") or die ("Cannot execute: 103");
		
		if(mysql_affected_rows()==1)
			return 1;
	
		return 0;	
	}
	
	public function query($query){
		$link=mysql_query($query) or die ("Cannot execute: 104");
		if( $link === TRUE || $link === FALSE ) {
			return $link;
		} else {
			$ret=array();
			while($result=mysql_fetch_array($link, MYSQL_ASSOC))
				$ret[]=$result;
			return $ret;
		}
	} 
}	